﻿using Core.Base;
using lingopen.Foxconn.RFID.Sdk;
using Core.Com;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using Reader.SFC.Models;
using Core.Enums;
using Core.Interfaces;
using System.IO.Ports;
using System.Drawing;

namespace Reader.SFC.Forms
{

    public partial class FrmRFID : Form
    {
        public FrmRFID()
        {
            InitializeComponent();
        }
        private void btnSetting_Click(object sender, EventArgs e)
        {
            //FrmConfig open = new FrmConfig();
            //if (open.ShowDialog() == DialogResult.OK)
            //{
            //    UnInit();
            //    Init();
            //}
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            try
            {
                //清除记录前先保存阅读记录和上传记录到json文本
                if (udps != null && udps.Count > 0)
                {
                    var time = DateTime.Now;
                    string json = udps.ToJson();
                    var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"UpdateLog({time.ToString("yyyyMMddHHmmss")}).json");

                    using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path, false, Encoding.UTF8))
                    {
                        sw.Write(json);
                    }
                    rtxt.Clear();
                    listPost.Clear();
                    listPass.Clear();
                    udps.Clear();
                    rlog.LogMessage("保存并清理成功!");
                }
            }
            catch (Exception ex)
            {
                rlog.LogMessage("Clear.Error=" + ex.Message);
            }


        }
        RichTextBoxLog rlog;
        Config config;
        private void FrmReader_Load(object sender, EventArgs e)
        {
            Init();
        }
        //public delegate void SetStateDelegate(Label lbl, string msg = "NG");
        //public void SetState(Label lbl, string msg = "NG")
        //{
        //    SetStateDelegate la = new SetStateDelegate(SetStateDe);
        //    lbl.Invoke(la, lbl, msg);
        //}
        //private void SetState(Label lbl, string msg = "NG")
        //{
        //    UpdateUI.UpdateUIControl(lbl, () =>
        //    {
        //        if (msg == "NG")
        //        {
        //            lbl.BackColor = System.Drawing.Color.Salmon;
        //        }
        //        else
        //        {
        //            lbl.BackColor = System.Drawing.Color.YellowGreen;
        //        }
        //        lbl.Text = msg;
        //    });



        //}
        private void SetState(Label lbl, string msg = "就緒")
        {
            UpdateUI.UpdateUIControl(lbl, () =>
            {
                if (msg == "NG")
                {
                    lbl.BackColor = System.Drawing.Color.Salmon;
                    lbl.ForeColor = System.Drawing.SystemColors.ButtonFace;
                }
                else if (msg == "OK")
                {
                    lbl.BackColor = System.Drawing.Color.YellowGreen;
                    lbl.ForeColor = System.Drawing.SystemColors.ButtonFace;
                }
                else
                {
                    lbl.BackColor = System.Drawing.Color.Ivory;
                    lbl.ForeColor = System.Drawing.SystemColors.WindowFrame;
                }
                lbl.Text = msg;
            });

        }

        void UnInit()
        {
            if (PostTag != null)
                PostTag -= FrmReader_PostTag;
            if (timUpd != null)
                timUpd.Elapsed -= TimUpd_Elapsed;
            //if (UpdateControl != null)
            //    UpdateControl -= UpdateListView;
            btnStop_Click(null, null);
            UnInitReader();
        }
        int ICheck = 0;
        int IPass = 0;
        /// <summary>
        /// 上传
        /// </summary> 
        private void FrmReader_PostTag(List<PostEPC> posts)
        {
            foreach (var post in posts)
            {
                string sFixEPC = post.sFixEPC;
                string sProEPC = post.sProEPc;
                if (this.rad3.Checked)
                {
                    if (sFixEPC.IsNull())
                    {
                        rlog.LogMessage("三码绑定，未读取到治具标签");
                        return;
                    }
                    if (sProEPC.IsNull())
                    {
                        rlog.LogMessage("三码绑定，未读取到产品标签");
                        return;
                    }
                }
                if (this.rad24.Checked)
                {
                    if (sProEPC.IsNull())
                    {
                        rlog.LogMessage($"二码绑定，未读取到{this.iProEPCLen}位标签");
                        return;
                    }
                    sFixEPC = string.Empty;
                }
                if (this.rad16.Checked)
                {
                    if (sFixEPC.IsNull())
                    {
                        rlog.LogMessage($"二码绑定，未读取到{this.iFixEPCLen}位标签");
                        return;
                    }
                    sProEPC = string.Empty;
                }
                SFC_Do_Check send = new SFC_Do_Check()
                {
                    request_id = config.Currency.host_ip.Replace(".", "") + DateTime.Now.ToString("yyyyMMddHHMMssfff") + GetSN(),
                    host_id = config.Currency.host_id,
                    host_ip = config.Currency.host_ip,
                    operation_user = config.Currency.operation_user,
                    process_name = config.Currency.process_name,
                    wrkst_type = config.Currency.wrkst_type,
                    wrkst_action = config.Currency.wrkst_action,
                    wrkst_name = config.Feed.wrkst_name, 
                    prod_code = sProEPC,
                    bind_code = new List<BindCode>(),
                    prod_type = config.Feed.prod_type,
                    resv1 = "",
                    resv2 = "",
                    resv3 = ""
                };
                string param = "data=" + send.ToJson();
                string str1 = string.Empty;
                try
                {
#if !DEBUG
                    str1 = HttpHelper.POST(url: config.Currency.Url1, param: param, time: 500);//上料确认 
#else
                    str1 = "{\"rc\":\"000\",\"rm\":\"OK\",\"barcode\":\"DR8805600D9MNBCAR01\",\"barCodeInfo\":{\"BAR_CODE\":\"DR8805600D9MNBCAR01\",\"BILL_NO\":\"701-1801060F\",\"BILL_CONFIG\":\"CONF\",\"CLIENT_CODE\":\"\",\"PRODUCT_ID\":\"1016034946\",\"PRODUCT_NAME\":\"701\",\"PHASE_ID\":\"2016035006\",\"PHASE_NAME\":\"Proto1\",\"PART_ID\":\"3016035326\",\"PART_NAME\":\"Housing\",\"PROCESS_ID\":\"4017036126\",\"PROCESS_NAME\":\"焊接\"},\"request_id\":\"101735817600000026\"}";
#endif
                }
                catch (Exception ex)
                {
                    rlog.LogError("上料確認.Error=" + ex.Message);
                    SetState(lblUpd, "NG");
                    continue;
                }

                string webRes;
                UpdResult udp1 = null;
                if (str1.IsNotNull())
                {
                    udp1 = str1.FromJson<UpdResult>();
                    webRes = udp1.rc;
                    if (udp1.rc != "000")
                    {
                        rlog.LogError("上料確認.Error=" + udp1.rm);
                    }

                }
                else
                    webRes = "失败";
                string res = "失败";
                if (webRes == "000") res = "成功";
                AddRowToListView(sFixEPC, sProEPC, config.Currency.host_id, res);
                if (webRes == "000")  //上料确认OK
                {
                    SetState(lblUpd, "OK");

                    //SoundHelper.PlayMySound("ok.wav");

                    string str2 = string.Empty;
                    try
                    {
                        SFC_Do_Pass pass = new SFC_Do_Pass()
                        {
                            request_id = config.Currency.host_ip.Replace(".", "") + DateTime.Now.ToString("yyyyMMddHHMMssfff") + GetSN(),
                            host_id = config.Currency.host_id,
                            host_ip = config.Currency.host_ip,
                            vendor_id = config.OverStation.vendor_id,//供應商編碼,填rtec
                            start_time = DateTime.Now.ToString("yyyyMMddHHmmss"),
                            end_time = DateTime.Now.ToString("yyyyMMddHHmmss"),
                            machine = config.OverStation.machine,
                            equipment_type = config.OverStation.equipment_type,//機台加工類型，默認填入L&Z，L代表鐳射機台，Z代表組裝幾台，必填參數
                            process_type = config.Currency.ProcessType,////默認填入Laser_Welding或Assembly，equipment_type為L時，上傳Laser_Welding；為Z時上傳Assembly，必填參數
                            machine_module = config.Currency.MachineModule,//填入機台管制編號，必填參數
                            location = config.OverStation.location,////機台所在位置：廠區-樓層 ，必填參數
                            bind_code = new List<BindCode>(),
                            line = config.OverStation.line,//产线编号
                            code_type = config.Currency.CodeType,//產品類型，必填參數（BG/Band/CG/FIXTURE，根據實際加工的產品類型填入默認值）
                            prod_barcode = sProEPC,// udp1.barcode,//条码，必须参数
                            prod_type = config.Currency.ProdType,//默認填入RFID或Barcode，定義prod_code參數為RFID標籤還是產品碼，必填參數 
                            process_name = config.Currency.process_name,
                            work_type = config.OverStation.work_type,
                            work_action = config.OverStation.work_action,
                            work_trans = config.OverStation.work_trans,//轉向條件(默認 deal) 
                            work_qis = config.OverStation.work_qis,//填入PASS 
                            process_revs = config.OverStation.process_revs,//填入程序版本号
                            glue_open_time = "",//間隔時間
                            vacum_exhaust_pressure = "",//压力
                            prod_cnt = "",//空值
                            product_no = "",//機種，空值
                            phase_no = "",//階段，空值
                            bill_no = "",//執行單，空值
                            config = "",////config，空值
                            wo_no = "",////工單，空值
                            prod_data = new List<ProdData>(),//產品在機台的加工參數，且prod_data欄位為必填參數
                            resv1 = "",
                            resv2 = "",
                            resv3 = ""
                        };
                        if (config.OverStation.bind_code != null && config.OverStation.bind_code.Count > 0)
                        {
                            pass.bind_code = config.OverStation.bind_code;
                            if (rad3.Checked)
                            {

                                pass.bind_code[0].code_sn = sFixEPC;
                            }
                        }

                        pass.prod_data.Add(new ProdData()
                        {

                        });

                        param = "data=" + pass.ToJson();
#if !DEBUG
                        str2 = HttpHelper.POST(url: config.Currency.Url2, param: param, time: 500);//过站确认 
#else
                        str2 = "{\"rc\":\"001\",\"rm\":\"OK\",\"barcode\":\"DR8805600D9MNBCAR01\",\"barCodeInfo\":{\"BAR_CODE\":\"DR8805600D9MNBCAR01\",\"BILL_NO\":\"701-1801060F\",\"BILL_CONFIG\":\"CONF\",\"CLIENT_CODE\":\"\",\"PRODUCT_ID\":\"1016034946\",\"PRODUCT_NAME\":\"701\",\"PHASE_ID\":\"2016035006\",\"PHASE_NAME\":\"Proto1\",\"PART_ID\":\"3016035326\",\"PART_NAME\":\"Housing\",\"PROCESS_ID\":\"4017036126\",\"PROCESS_NAME\":\"焊接\"},\"request_id\":\"10173581760000000021\"}";
#endif
                    }

                    catch (Exception ex)
                    {

                        rlog.LogError("過站確認.Error=" + ex.Message);
                        SetState(lblPass, "NG");
                        continue;
                    }
                    if (str2.IsNotNull())
                    {
                        UpdResult udp2 = str2.FromJson<UpdResult>();
                        webRes = udp2.rc;
                        if (udp2.rc != "000")
                        {
                            rlog.LogError("過站確認.Error=" + udp2.rm);
                        }

                    }
                    res = "失败";
                    if (webRes == "000") res = "成功";
                    AddRowToListView2(sFixEPC, sProEPC, config.Currency.host_id, res);
                    if (webRes == "000")  //過站確認OK
                    {
                        SetState(lblPass, "OK");

                    }
                    else
                    {
                        SetState(lblPass, "NG");
                        SoundHelper.PlayMySound("error.wav");
                        continue;
                    }
                }
                else
                {
                    SetState(lblUpd, "NG");
                    SoundHelper.PlayMySound("error.wav");
                    continue;
                }
            }
        }
        static List<SaveUdp> udps = new List<SaveUdp>();

        void AddRowToListView(string sFixEPC, string sProEPC, string sEquipNO, string webRes)
        {

            UpdateUI.UpdateUIControl(listPost, () =>
            {

                this.listPost.Items.Add(new ListViewItem((this.listPost.Items.Count + 1).ToString())
                {
                    SubItems = {
                      sFixEPC,
                      sProEPC,
                      sEquipNO,
                      webRes,
                      DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                },
                    ForeColor = (webRes == "成功" ? System.Drawing.Color.Green : Color.Red)
                });
                if (webRes == "成功")
                {
                    ICheck++;
                    lblChk.Text = "上料確認      計數:【" + ICheck + "】";
                }
                this.listPost.Items[this.listPost.Items.Count - 1].EnsureVisible();

            });

        }
        void AddRowToListView2(string sFixEPC, string sProEPC, string sEquipNO, string webRes)
        {

            UpdateUI.UpdateUIControl(listPass, () =>
            {
                udps.Add(new SaveUdp()
                {
                    FixEPC = sFixEPC,
                    ProEPC = sProEPC,
                    EquipNO = sEquipNO,
                    Res = webRes
                });
                this.listPass.Items.Add(new ListViewItem((this.listPass.Items.Count + 1).ToString())
                {
                    SubItems = {
                      sFixEPC,
                      sProEPC,
                      sEquipNO,
                      webRes,
                      DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                },
                    ForeColor = (webRes == "成功" ? System.Drawing.Color.Green : Color.Red)
                });
                if (webRes == "成功")
                {
                    IPass++;
                    lblPas.Text = "過站確認      計數:【" + ICheck + "】";
                }

                this.listPass.Items[this.listPass.Items.Count - 1].EnsureVisible();

            });

        }
        private void TimUpd_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            timUpd.Stop();
            UpdateUI.UpdateUIControl(listRead, () =>
            {
                listRead.Items.Clear();
                if (listPost.Items.Count == 100)
                    listPost.Items.Clear();
                if (listPass.Items.Count == 100)
                {
                    listPass.Items.Clear();

                    if (udps != null && udps.Count > 0)
                    {
                        var time = DateTime.Now;
                        string json = udps.ToJson();
                        var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"UpdateLog({time.ToString("yyyyMMddHHmmss")}).json");

                        using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path, false, Encoding.UTF8))
                        {
                            sw.Write(json);
                        }
                        rtxt.Clear();
                        udps.Clear();
                        rlog.LogMessage("保存并清理成功!");
                    }
                }
                for (int index = 0; index < scanTags.Count; ++index)
                    this.listRead.Items.Add(new ListViewItem()
                    {
                        Text = (index + 1).ToString(),
                        SubItems ={
                              scanTags[index].epc,
                              scanTags[index].antNo.ToString(),
                              scanTags[index].count.ToString(),
                              scanTags[index].devNo.ToString()
                            }
                    });
            });
            List<PostEPC> post = new List<PostEPC>();
            for (int index = 0; index < scanTags.Count; ++index)
            {
                EPC epcData1 = new EPC();
                EPC epcData2 = new EPC();

                string str1 = string.Empty;
                string str2 = string.Empty;
                if (scanTags[index].epc.Length == this.iProEPCLen)
                {
                    if (scanTags[index].count > epcData1.count)
                    {
                        epcData1 = scanTags[index];
                        str1 = epcData1.epc;
                    }
                }
                else if (scanTags[index].epc.Length == this.iFixEPCLen && scanTags[index].count > epcData2.count)
                {
                    epcData2 = scanTags[index];
                    str2 = epcData2.epc;

                }
                post.Add(new PostEPC(str1, str2));
            }
            var postfilter = (from p in post
                              where p.sProEPc.IsNotNull()
                              select p).ToList();
            PostTag?.Invoke(postfilter);
            scanTags.Clear();
        }

        static System.Timers.Timer timUpd;
        static int SN = 0;
        string GetSN()
        {
            SN++;
            return (Math.Pow(10, 6).ToString() + SN).ToString().Substring(1);
        }
        bool Init()
        {
            btnTest.Visible = false;
            btnTest2.Visible = false;
            btnStart.Enabled = false;
            btnStop.Enabled = false;
            bool flag = false;
            //日志初始化
            if (rlog == null)
                rlog = new RichTextBoxLog(rtxt);
            config = Program.AppConfig;
            if (config == null)
            {
                flag = false;
            }
            else
            {
                if (config.Currency.Url1.IsNull())
                {
                    rlog.LogMessage("请在【设置】中设置URL1地址!");
                    flag = false;
                }
                if (config.Currency.Url2.IsNull())
                {
                    rlog.LogMessage("请在【设置】中设置URL2地址!");
                    flag = false;
                }
                if (config.System.Port.IsNull())
                {
                    rlog.LogMessage("请在【设置】中设置端口号!");
                    flag = false;
                }
                if (config.Currency.host_id.IsNull())
                {
                    rlog.LogMessage("请在【设置】中设置机台码!");
                    flag = false;
                }

                this.Text = config.System.AppName + " " + config.System.Version;
                SN = 0;
                lblMachineID.Text = config.Currency.host_id;
                lblPort.Text = config.System.Port;
                iProEPCLen = config.System.ProEPCLen24;
                iFixEPCLen = config.System.FixEPCLen16;
                if (timUpd == null)
                {
                    timUpd = new System.Timers.Timer(config.System.ReadOverTime);
                }
                else
                {
                    timUpd.Interval = config.System.ReadOverTime;
                }
                timUpd.Elapsed += TimUpd_Elapsed;
                PostTag += FrmReader_PostTag;

                flag = true;
            }
            //RFID设备连接状态
            if (flag && !InitReader())
            {
                flag = false;
            }
            //上传状态
            if (!flag)
            {
                btnStart.Enabled = false;
                btnStop.Enabled = false;
                rlog.LogMessage("初始化失败!");
            }
            else
            {
                btnStart.Enabled = true;
                btnStop.Enabled = false;
                rlog.LogMessage("准备就绪!");
                //UpdateControl += UpdateListView;
            }
            return flag;
        }

        //Core.Com.SerialPortHelper serialPort;
        private bool InitReader()
        {
            try
            {
                if (config.System.Port.IsNull())
                {
                    rlog.LogMessage("请在【设置】中设置端口号!");
                    return false;
                }

                if (config.System.Power == null || config.System.Power <= 0)
                {
                    config.System.Power = 30;
                }
                int index = 0;
                byte[] numArray = new byte[32];
                byte[] bytes = Encoding.ASCII.GetBytes(config.System.Port);
                while (index < 50 && this.hDev[index] != 0)
                    ++index;
                if (index == 50)
                {
                    rlog.LogMessage($"{config.System.Port}无法访问!");
                    SetState(lblRfid, "NG");
                    return false;
                }

                PANT_CFG pantCfg = new PANT_CFG(); //设置信号强度
                pantCfg.power = new uint[4];
                uint result = (uint)config.System.Power;
                if (result > 30U)
                    result = 30U;
                pantCfg.power[0] = result * 10U;
                pantCfg.power[1] = result * 10U;
                pantCfg.power[2] = result * 10U;
                pantCfg.power[3] = result * 10U;

                if (NR2k.ConnectDev(ref this.hDev[index], bytes) == 0)
                {
                    byte[] pVer = new byte[32];
                    NR2k.GetDevVersion(this.hDev[index], pVer);
                    SetState(lblRfid, "OK");
                }
                else
                {
                    SetState(lblRfid, "NG");
                    rlog.LogMessage($"{config.System.Port}连接失败!"); btnTest.Visible = true;
                    btnTest2.Visible = true;
                    return false;
                }

            }
            catch (Exception ex)
            {
                SetState(lblRfid, "NG");
                rlog.LogMessage($"启动异常:{ex.Message}");
                btnTest.Visible = true;
                btnTest2.Visible = true;
                return false;
            }
            return true;
        }
        byte[] reader = new byte[32];
        private void SerialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            SerialPort sp = (SerialPort)sender;
            Console.Write(string.Format("{0:X2} ", sp.ReadByte()));
            rlog.LogSuccess(string.Format("{0:X2} ", sp.ReadByte()));
        }

        private bool UnInitReader()
        {
            bool flag = false;
            //断开设备
            for (int index = 0; index < 50; ++index)
            {
                if (this.hDev[index] != 0)
                {
                    NR2k.DisconnectDev(ref this.hDev[index]);
                    flag = true;
                }
            }
            if (!flag)
            {
                rlog.LogMessage($"断开COM失败!");
            }
            fun -= HandleData;
            this.btnStart.Enabled = true;
            this.btnStop.Enabled = false;
            return flag;
        }



        static string epc = "";
        static List<EPC> scanTags = new List<EPC>(); //扫描记录
        static List<EPC> checkTags = new List<EPC>();//上料确认
        static List<EPC> passTags = new List<EPC>();//过站确认
        public delegate void UpdateControlEventHandler();
        //static event UpdateControlEventHandler UpdateControl;
        static event PostTagEventHandler PostTag;

        public delegate void PostTagEventHandler(List<PostEPC> postEpc);//string sProEPc, string sFixEPC);

        int iProEPCLen = 24;
        int iFixEPCLen = 16;
        public void HandleData(int hDev, int cmdID, IntPtr pData, int length, IntPtr pHost)
        {
            try
            {

                epc = "";
                byte[] destination = new byte[32];
                byte[] numArray = new byte[32];
                //if (length <= 2) return; //1 心跳

                if (length < 5)
                {
                    Marshal.Copy(pData, destination, 0, length);
                    //Marshal.Copy(pHost, numArray, 0, length);
                    for (int index = 0; index < length; ++index)
                        epc += string.Format("{0:X2} ", (object)destination[index]);
                    rlog.LogMessage(epc);
                    return;
                }
                //4 触发完成

                //if (length < 5 || length > 30)
                //return;

                Marshal.Copy(pData, destination, 0, length);
                Marshal.Copy(pHost, numArray, 0, 16);
                for (int index = 0; index < length - 4; ++index)
                    epc += string.Format("{0:X2} ", (object)destination[index]);
                epc = epc.Replace(" ", "");
                var exsit = scanTags.Where(p => p.epc == epc);
                if (exsit.Any())
                {
                    var entity = scanTags.Where(p => p.epc == epc).FirstOrDefault();
                    entity.count++;
                    entity.antNo = (byte)((uint)destination[length - 1] + 1U);
                }
                else
                {
                    string str1 = destination[length - 3].ToString();
                    string str2 = destination[length - 2].ToString();
                    scanTags.Add(new EPC()
                    {
                        epc = epc,
                        antNo = destination[length - 1],
                        devNo = Encoding.Default.GetString(numArray),
                        count = (Convert.ToInt32(str1, 10) * 256 + Convert.ToInt32(str2, 10))
                    });
                }
                timUpd?.Start();
            }
            catch (Exception ex)
            {
                rlog.LogMessage("读取标签异常:" + ex.Message);
            }
        }

        private int[] hDev = new int[50];
        private NR2k.HANDLE_FUN fun;

        private void btnStart_Click(object sender, EventArgs e)
        {
            Start();
        }

        private void FrmReader_FormClosing(object sender, FormClosingEventArgs e)
        {
            UnInit();
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            Stop();
        }
        public string GetName()
        {
            return lblMachineID.Text;
        }



        public bool Start()
        {
            try
            {

                bool flag = false;
                fun += HandleData;
                for (int i = 0; i < 50; ++i)
                {
                    if (this.hDev[i] != 0)
                    {
                        NR2k.BeginInv(this.hDev[i], fun);
                        flag = true;
                    }
                }
                if (!flag)
                {
                    rlog.LogMessage("设备尚未连接!");
                    return false;
                }
                this.btnStart.Enabled = false;
                this.btnStop.Enabled = true;
                rlog.LogMessage("已启动");

                return true;

            }
            catch (Exception ex)
            {
                rlog.LogMessage($"启动异常:{ex.Message}");
                return false;
            }

        }

        public bool Stop()
        {
            try
            {

                //停止监听
                bool flag = false;
                //serialPort?.Close();
                //return true;
                for (int index = 0; index < 50; ++index)
                {
                    if (this.hDev[index] != 0)
                    {
                        NR2k.StopInv(this.hDev[index]);
                        flag = true;
                    }
                }
                if (!flag)
                {
                    rlog.LogMessage("设备尚未连接!");
                    return false;

                }
                else
                {
                    this.btnStart.Enabled = true;
                    this.btnStop.Enabled = false;
                    rlog.LogMessage("已停止");
                    return true;
                }
            }
            catch (Exception ex)
            {
                rlog.LogMessage($"停止异常:{ex.Message}");
                return false;
            }
        }

        public bool PowerON(Action<string> callback)
        {
            return Init();
        }

        public bool PowerOFF()
        {
            UnInit();
            return true;
        }

        private void btnInit_Click(object sender, EventArgs e)
        {
            //FrmBind open = new FrmBind();
            //open.FormClosed += Open_FormClosed;
            //open.Show();
            //this.Hide();

        }

        private void Open_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.Show();
        }

        private void btnTest_Click(object sender, EventArgs e)
        {

            SFC_Do_Check send = new SFC_Do_Check()
            {
                request_id = config.Currency.host_ip.Replace(".", "") + DateTime.Now.ToString("yyyyMMddHHMMssfff") + GetSN(),
                host_id = config.Currency.host_id,
                host_ip = config.Currency.host_ip,
                operation_user = config.Currency.operation_user,
                process_name = config.Currency.process_name,
                wrkst_type = config.Currency.wrkst_type,
                wrkst_action = config.Currency.wrkst_action,
                wrkst_name = config.Feed.wrkst_name,
                prod_code = config.OverStation.EPC,
                bind_code = new List<BindCode>(),
                prod_type = config.Feed.prod_type,
                resv1 = "",
                resv2 = "",
                resv3 = ""
            };
            string param = "data=" + send.ToJson();
            string str1 = string.Empty;
            try
            {
#if !DEBUG
                str1 = HttpHelper.POST(url: config.Currency.Url1, param: param, time: 500);//上料确认 
#else
                str1 = "{\"rc\":\"000\",\"rm\":\"OK\",\"barcode\":\"DR8805600D9MNBCAR01\",\"barCodeInfo\":{\"BAR_CODE\":\"DR8805600D9MNBCAR01\",\"BILL_NO\":\"701-1801060F\",\"BILL_CONFIG\":\"CONF\",\"CLIENT_CODE\":\"\",\"PRODUCT_ID\":\"1016034946\",\"PRODUCT_NAME\":\"701\",\"PHASE_ID\":\"2016035006\",\"PHASE_NAME\":\"Proto1\",\"PART_ID\":\"3016035326\",\"PART_NAME\":\"Housing\",\"PROCESS_ID\":\"4017036126\",\"PROCESS_NAME\":\"焊接\"},\"request_id\":\"101735817600000026\"}";
#endif
                rlog.LogSuccess(str1);
            }
            catch (Exception ex)
            {
                rlog.LogError("上料确认.Error=" + ex.Message);
                SetState(lblUpd, "NG");
            }
        }

        private void btnTest2_Click(object sender, EventArgs e)
        {
            string str2 = string.Empty;
            try
            {
                SFC_Do_Pass pass = new SFC_Do_Pass()
                {
                    request_id = config.Currency.host_ip.Replace(".", "") + DateTime.Now.ToString("yyyyMMddHHMMssfff") + GetSN(),
                    host_id = config.Currency.host_id,
                    host_ip = config.Currency.host_ip,
                    vendor_id = config.OverStation.vendor_id,//供應商編碼,填rtec
                    start_time = DateTime.Now.ToString("yyyyMMddHHmmss"),
                    end_time = DateTime.Now.ToString("yyyyMMddHHmmss"),
                    equipment_type = config.OverStation.equipment_type,//機台加工類型，默認填入L&Z，L代表鐳射機台，Z代表組裝幾台，必填參數
                    process_type = config.Currency.ProcessType,////默認填入Laser_Welding或Assembly，equipment_type為L時，上傳Laser_Welding；為Z時上傳Assembly，必填參數
                    machine_module = config.Currency.MachineModule,//填入機台管制編號，必填參數
                    location = config.OverStation.location,////機台所在位置：廠區-樓層 ，必填參數
                    bind_code = new List<BindCode>(),
                    line = config.OverStation.line,//产线编号
                    code_type = config.Currency.CodeType,//產品類型，必填參數（BG/Band/CG/FIXTURE，根據實際加工的產品類型填入默認值）
                    prod_barcode = config.OverStation.EPC,//条码，必须参数
                    prod_type = config.Currency.ProdType,//默認填入RFID或Barcode，定義prod_code參數為RFID標籤還是產品碼，必填參數 
                    process_name = config.Currency.process_name,
                    work_type = config.OverStation.work_type,
                    work_action = config.OverStation.work_action,
                    work_trans = config.OverStation.work_trans,//轉向條件(默認 deal) 
                    work_qis = config.OverStation.work_qis,//填入PASS 
                    process_revs = config.OverStation.process_revs,//填入程序版本号
                    glue_open_time = "",//間隔時間
                    vacum_exhaust_pressure = "",//压力
                    prod_cnt = "",//空值
                    product_no = "",//機種，空值
                    phase_no = "",//階段，空值
                    bill_no = "",//執行單，空值
                    config = "",////config，空值
                    wo_no = "",////工單，空值
                    prod_data = new List<ProdData>(),//產品在機台的加工參數，且prod_data欄位為必填參數
                    resv1 = "",
                    resv2 = "",
                    resv3 = ""
                };
                if (config.OverStation.bind_code != null && config.OverStation.bind_code.Count > 0)
                {
                    pass.bind_code = config.OverStation.bind_code;
                }
                pass.prod_data.Add(new ProdData()
                {

                });

                var param = "data=" + pass.ToJson();
#if !DEBUG
                str2 = HttpHelper.POST(url: config.Currency.Url2, param: param, time: 500);//过站确认 
#else
                str2 = "{\"rc\":\"000\",\"rm\":\"OK\",\"barcode\":\"DR8805600D9MNBCAR01\",\"barCodeInfo\":{\"BAR_CODE\":\"DR8805600D9MNBCAR01\",\"BILL_NO\":\"701-1801060F\",\"BILL_CONFIG\":\"CONF\",\"CLIENT_CODE\":\"\",\"PRODUCT_ID\":\"1016034946\",\"PRODUCT_NAME\":\"701\",\"PHASE_ID\":\"2016035006\",\"PHASE_NAME\":\"Proto1\",\"PART_ID\":\"3016035326\",\"PART_NAME\":\"Housing\",\"PROCESS_ID\":\"4017036126\",\"PROCESS_NAME\":\"焊接\"},\"request_id\":\"10173581760000000021\"}";
#endif
                rlog.LogSuccess(str2);
            }

            catch (Exception ex)
            {

                rlog.LogError("过站确认.Error=" + ex.Message);
                SetState(lblPass, "NG");
            }
        }

        private void rad24_CheckedChanged(object sender, EventArgs e)
        {

        }
    }
    public class PostEPC
    {

        public PostEPC(string str1, string str2)
        {
            this.sProEPc = str1;
            this.sFixEPC = str2;
        }

        public string sProEPc { get; set; }
        public string sFixEPC { get; set; }
    }
}
